// 配置axios基地址
axios.defaults.baseURL = 'https://hmajax.itheima.net'

// 抽取轻提示函数
function showToast(msg) {
  const toastDom = document.querySelector('.my-toast')
  const toast = new bootstrap.Toast(toastDom)
  document.querySelector('.toast-body').innerText = msg
  toast.show()
}

function checkLogin() {
  const token = localStorage.getItem('token')
  if (token === null) {
    showToast('请先登录')
    setTimeout(() => {
      location.href = 'login.html'
    }, 1500)
  }
}

function renderUsername() {
  const username = localStorage.getItem('username')
  document.querySelector('.username').innerText = username
}

function registerLogout() {
  document.querySelector('#logout').addEventListener('click', () => {
    localStorage.removeItem('username')
    localStorage.removeItem('token')
    location.href = 'login.html'
  })
}

axios.interceptors.request.use(function (config) {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers['Authorization'] = token
  }
  return config;
}, function (error) {
  return Promise.reject(error);
});


axios.interceptors.response.use(function (response) {
  return response.data;
}, function (error) {
  if (error.response.status === 401) {
    showToast('请重新登录')
    localStorage.removeItem('token')
    localStorage.removeItem('username')
    setTimeout(() => {
      location.href = 'login.html'
    }, 1500)
  }
  return Promise.reject(error);
});
